package config

import (
	"errors"
	"github.com/spf13/viper"
	"sync"
)

var confOnce sync.Once
var confInstance ApplicationConfig
var viperInstance *viper.Viper

type Server struct {
	Address string `yaml:"address"`
	Port    int    `yaml:"port"`
}

type Logging struct {
	RootLevel string `yaml:"rootLevel"`
}

type ApplicationConfig struct {
	Server      *Server  `yaml:"server"`
	Logging     *Logging `yaml:"logging"`
	Initialized bool     `transient:"Initialized"`
}

type Reader interface {
	Instance() *ApplicationConfig
}

func ReaderInstance() (Reader, error) {
	confOnce.Do(func() {
		vp := viper.New()
		_ = loadConfig(vp)
	})
	if !confInstance.Initialized {
		return nil, errors.New("config not initialized")
	}
	return &confInstance, nil
}

func (a *ApplicationConfig) Instance() *ApplicationConfig {
	return &confInstance
}

func (a *ApplicationConfig) Load() error {
	if _, err := ReaderInstance(); err != nil {
		return err
	} else {
		return nil
	}
}

func (a *ApplicationConfig) Reload() error {
	return loadConfig(viperInstance)
}

func loadConfig(vp *viper.Viper) error {
	return nil
}
